//
//  ViewController.swift
//  Thread
//
//  Created by wsk on 2023/10/27.
//

import UIKit

class PrintLetterWithSemaphore {
    var semaphore: dispatch_semaphore_t
    
    init() {
        self.semaphore = DispatchSemaphore(value: 0)
    }
    
    func printLetterA() {
        for _ in 0..<3 {
            print("A")
            /// 执行完毕signal之后，如果别的线程在wait，则不会立即执行下面的代码，而是去立即唤醒wait中的线程
            semaphore.signal()
            /// wait 后面的执行需要等待其他线程的signal唤醒才能继续
            semaphore.wait()
        }
    }
    
    func printLetterB() {
        for _ in 0..<3 {
            semaphore.wait()
            print("B")
            semaphore.signal()
        }
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let printer = PrintLetterWithSemaphore()
        
        let queue1 = DispatchQueue(label: "1", qos: .background)
        let queue2 = DispatchQueue(label: "2", qos: .background)
        
        queue1.async {
            printer.printLetterA()
        }
        
        queue2.async {
            printer.printLetterB()
        }
        // 打印结果，交替的打印 A 和 B
        //A
        //B
        //A
        //B
        //A
        //B
    }
}

